# encoding: utf-8

class ReviewsController < ApplicationController
  before_filter :find_review, :only => [:show, :edit, :update, :destroy]
  
  def index
    unless params[:item_id].blank?
      @reviews = Item.find(params[:item_id]).ratings.valid.filter(params).paginate :page => params[:page], :per_page => 30
    else
      @reviews = ItemReview.active.paginate :page => params[:page], :per_page => 30
    end
  end
  
  def show
  end
  
  def new
    @review = ItemReview.new
  end
  
  def create
    @review = ItemReview.new(params[:review])
    if @review.save
      flash[:notice] = "操作成功."
      redirect_to params[:save_and_new].blank? ? edit_review_path(@review) : new_review_path
    else
      render 'new'
    end
  end
  
  def edit
  end
  
  def update
    if @review.update_attributes(params[:review])
      flash[:notice] = "操作成功."
      redirect_to params[:save_and_new].blank? ? edit_review_path(@review) : new_review_path
    else
      render 'edit'
    end
  end
  
  def destroy
    @review.del
    flash[:notice] = "操作成功."
    redirect_to admin_reviews_url
  end
  
  def update_status
    if params[:ids].blank? or params[:ids].all?{|id| id.blank? }
      flash[:error] = "操作失败."
    else
      status = params[:status].blank? ? 0 : params[:status].to_i
      ItemReview.update_all("status = #{status}", "id IN (#{params[:ids].join(',')})")
      flash[:notice] = "操作成功."
    end
    redirect_to reviews_url
  end
  
  private

  def find_review
    @review = ItemReview.find(params[:id])
  end
end
